<template>
    <el-select
        ref="selectRef"
        :model-value="props.modelValue"
        v-bind="attrs"
        :filter-method="filterMethod"
        @update:model-value="(value:unknown) => emits('update:modelValue', value)"
        @visible-change="visibleChange"
    >
        <slot />
    </el-select>
</template>

<script lang="ts">
export default { name: 'ReSelect' }
</script>

<script lang="ts" setup>

import { getCurrentInstance, ComponentInternalInstance, reactive, ref, unref, nextTick, createVNode, onMounted, defineComponent, useAttrs, useSlots } from 'vue'

const attrs = useAttrs()

const emits = defineEmits(['update:modelValue'])
const { proxy }:any = getCurrentInstance() as ComponentInternalInstance

const props = defineProps({
    // eslint-disable-next-line vue/require-default-prop
    modelValue: null,
    // eslint-disable-next-line vue/require-default-prop
    filterMethod: null,
})
const selectRef = ref()

const state = reactive({
    hiddenList: [] as unknown[],
})

const visibleChange = (visible:boolean) => {
    if (!visible) filterMethod('')
}

let filterTimer:any = null
const filterMethod = (value:string) => {
    if (attrs.filterable === undefined || attrs.filterable === false) return
    let hiddenList:unknown[] = []
    if (typeof props.filterMethod === 'function') {
        hiddenList = props.filterMethod(value) || []
    } else {
        hiddenList = []
        selectRef.value.options.forEach((option) => {
            if (option.label.indexOf(value) === -1) hiddenList.push(option.value)
        })
    }
    clearTimeout(filterTimer)
    filterTimer = setTimeout(() => {
        displayOptions(hiddenList)
    }, 200)
}

const displayOptions = (hiddenList = state.hiddenList) => {
    state.hiddenList = hiddenList
    selectRef.value.options.forEach((option) => {
        if (hiddenList.indexOf(option.value) !== -1) {
            option.$el.style.display = 'none'
        } else {
            option.$el.style.display = 'list-item'
        }
    })
}

onMounted(() => {

})

defineExpose({
    displayOptions,
})
</script>
